# -*- coding:utf-8 -*-

import os
import sys
import getpass
import time

dir_path = os.path.dirname(__file__)
deadline_path = os.path.join(dir_path, 'Deadline_py3')
print(deadline_path)
sys.path.append(deadline_path)
# sys.path.insert(0,deadline_path)


HOST = '192.168.8.3'
PORT = 8082

username = getpass.getuser()
print(username)

try:
    import DeadlineConnect as Connect
    connectionObject = Connect.DeadlineCon(HOST, PORT)
except Exception as Connect_ERR:
    print('Connect_ERR:',Connect_ERR)


# pools = connectionObject.Pools.GetPoolNames()

# # 获取所有jobs
# all_jobs = connectionObject.Jobs.GetJobs()
# print(len(all_jobs))
# stats = []
# for i in all_jobs:
#     stat = i.get('Stat','')
#     if stat not in stats:
#         stats.append(stat)
#
# print(stats)



# 获取所有失败的任务
#Active, Suspended, Completed, Failed, and Pending
# all_failed_jobs = connectionObject.Jobs.GetJobsInState('Failed')
# print(len(all_failed_jobs))

# #获取所有已经完成的任务
# all_completed_jobs = connectionObject.Jobs.GetJobsInState('Completed')
# print(len(all_completed_jobs))

# 获取所有暂停的任务
# all_suspended_jobs = connectionObject.Jobs.GetJobsInState('Suspended')
# print(len(all_suspended_jobs))

# 获取所有正在依赖挂起的任务
# all_pending_jobs = connectionObject.Jobs.GetJobsInState('Pending')
# print(len(all_pending_jobs))

# 获取所有激活的任务，包括Queued 排队 and Rendering正在渲染任务
# all_active_jobs = connectionObject.Jobs.GetJobsInState('Active')
# print(len(all_active_jobs))



# 获取某人的所有Jobs
def get_jobs_by_username(username,ids=[]):
    start = time.time()
    if ids:
        all_active_jobs = connectionObject.Jobs.GetJobs(ids)
    else:
        # all_active_jobs = connectionObject.Jobs.GetJobsInState('Active')
        all_active_jobs = connectionObject.Jobs.GetJobs()

    status_map = {0:'Unknown',1:'Active',2:'Suspended',3:'Completed',4:'Failed',6:'Pending'}

    data_list = []
    for a in all_active_jobs:
        data = {}
        Stat = a.get('Stat',0)
        if Stat in [1,2,3,4,6]:
            Props = a.get('Props',{})
            user = Props.get('User','')
            ListedSlaves = Props.get('ListedSlaves',[])
            if user == username:
                Name = Props.get('Name','')
                _id = a.get('_id','')
                data['Name'] = Name
                data['_id'] = _id
                data['Stat'] = Stat
                data['ListedSlaves'] = ListedSlaves
                data['status'] = status_map[Stat]
                data_list.append(data)
    end = time.time()
    print('执行速度:',end-start)
    return data_list

# username = 'chenhj'
# data_list = get_jobs_by_username(username)
# print(len(data_list))
#
# for data in data_list:
#     print(data['Name'])



# # 获取Active Jobs
# def get_active_jobs(username=None):
#     start = time.time()
#
#     all_active_jobs = connectionObject.Jobs.GetJobsInState('Active')
#
#     status_map = {0:'Unknown',1:'Active',2:'Suspended',3:'Completed',4:'Failed',6:'Pending'}
#
#     data_list = []
#     for a in all_active_jobs:
#         data = {}
#         Stat = a.get('Stat',0)
#         Props = a.get('Props',{})
#         user = Props.get('User','')
#         Name = Props.get('Name', '')
#         _id = a.get('_id', '')
#         data['Name'] = Name
#         data['_id'] = _id
#         data['Stat'] = Stat
#         data['status'] = status_map[Stat]
#         if username:
#             if user == username:
#                 data_list.append(data)
#         else:
#             data_list.append(data)
#     end = time.time()
#     print('执行速度:',end-start)
#     return data_list
#
#
# active_jobs = get_active_jobs()
# print(len(active_jobs))
# print(active_jobs[0])


# 获取单个job信息
job_id = '60fcef0d6798fb23506ea352'
job_info = connectionObject.Jobs.GetJob(job_id)
print(job_info)


"""  *****   Job Reports      *****  """
# job_id = '60fa6d3a6798fb23506ea0e5'

# # 获取所有 Job Error Reports Contents
# jer = connectionObject.JobReports.GetAllJobErrorReportsContents(job_id)
# print(jer)

# # 获取所有 Job Log Reports Contents
# jlrc = connectionObject.JobReports.GetAllJobLogReportsContents(job_id)
# print(jlrc)

# # 获取所有Job Reports
# jr = connectionObject.JobReports.GetAllJobReports(job_id)
# print(jr)

# # 获取所有 Job Reports Contents
# jrc = connectionObject.JobReports.GetAllJobReportsContents(job_id)
# print(jrc)

# # 获取所有Job Requeue Reports Contents
# jrrc = connectionObject.JobReports.GetAllJobRequeueReportsContents(job_id)
# print(jrrc)


# # 获取 Job Log Reports
# jlr = connectionObject.JobReports.GetJobLogReports(job_id)
# print(jlr)


# # 获取 Job Error Reports
# jer = connectionObject.JobReports.GetJobErrorReports(job_id)
# print(jer)







"""  *****   Tasks      *****  """

# 注意 tasks求取，都必须要传入一个job id

# _id = '60fa6d3a6798fb23506ea0e5'
# tasks = connectionObject.Tasks.GetJobTasks(_id)
# print(tasks)

# job_id = '60fa6d3a6798fb23506ea0e5'
# task_id = 0

# # 获取 Task Log Reports
# tlogs = connectionObject.TaskReports.GetTaskLogReports(job_id,task_id)
# print(tlogs)

# # 获取 Task Error Reports
# telogs = connectionObject.TaskReports.GetTaskErrorReports(job_id,task_id)
# print(telogs)



# # 获取所有 Task Logs Reports Contents
# tclogs = connectionObject.TaskReports.GetAllTaskLogReportsContents(job_id,task_id)
# print(tclogs)



# # 获取所有 Task Reports
# tr = connectionObject.TaskReports.GetAllTaskReports(job_id,task_id)
# print(tr)

# # 获取所有 Task Error Reports Contents
# ter = connectionObject.TaskReports.GetAllTaskErrorReportsContents(job_id,task_id)
# print(ter)






"""  *****   机器限制      *****  """

# all_tasks = connectionObject.Jobs.SetJobMachineLimit()
# all_tasks = connectionObject.Jobs.SetJobMachineLimitListedSlaves()

# # 获取机器
#
# workers = connectionObject.Slaves.GetSlaveNames()
# print(len(workers))
# print(workers)


# 获取机器信息
# infos = connectionObject.Slaves.GetSlavesSettings()
# infos



# # 设置黑名单
# slaveList = ['TX-chenyi']
# result = connectionObject.Jobs.SetJobMachineLimitListedSlaves(job_id,slaveList)
# print(result)

